package com.zxl.service.impl;


import com.zxl.mapper.MmMessageMapper;
import com.zxl.entities.MmMessage;
import com.zxl.handle.MmMessageHandler;
import com.zxl.model.dto.MmMessageDto;
import com.zxl.service.MmMessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MmMessageServiceImpl implements MmMessageService {

    @Resource
    private MmMessageHandler msgHandler;//对应设计图第6步用到的。

    @Resource
    private MmMessageMapper mmMessageMapper;

    private static final Logger LOGGER = LoggerFactory.getLogger(MmMessageServiceImpl.class);

    /**
     * 设计图第2步，接收"待发送"消息，把消息保持为“待发送”状态
     *
     * @param msgDTO
     */
    @Transactional
    @Override
    public void prepareMsg(MmMessageDto msgDTO) {
        MmMessage msg = new MmMessage();
        BeanUtils.copyProperties(msgDTO, msg);
        //tx_msg表`status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '消息状态 0=待发送 1=已发送 '
        msg.setStatus((byte) 0);
        this.mmMessageMapper.insertSelective(msg);
    }

    /**
     * 设计图第5步，确认消息可以发送了，把消息状态改为“已发送”
     *
     * @param msgDTO
     */
    @Transactional
    @Override
    public void confirmMsg(MmMessageDto msgDTO) {
        MmMessage msg = new MmMessage();
        msg.setMsgId(msgDTO.getMsgId());
        msg = this.mmMessageMapper.selectOne(msg);

        //tx_msg表`status`消息状态 0=待发送 1=已发送 '
        msg.setStatus((byte) 1);
        int i = this.mmMessageMapper.updateByPrimaryKeySelective(msg);

        if (i > 0) {
            // 对应设计图的第6步骤，确认消息可以发出去给RabbitMQ了，发送消息
            this.msgHandler.send(msg.getRoutingKey(), msg.getJsonMsg());
        }
    }

    @Transactional
    @Override
    public void deleteMsg(MmMessageDto msgDTO) {
        LOGGER.info("delete-msg............" + msgDTO.getMsgId());
        MmMessage msg = new MmMessage();
        msg.setMsgId(msgDTO.getMsgId());
        this.mmMessageMapper.delete(msg);
    }

    /**
     * 下面是给定时任务xxl-job配合使用的，不是一键生成的mybatis代码
     * SELECT * FROM tx_msg m WHERE `status`=#{status}  and TIMESTAMPDIFF(MINUTE,create_time, NOW())>#{time}
     *
     * @param t
     * @return
     */
    @Override
    public List<MmMessage> selectOverdueMsgByNotSend(int t) {
        return this.mmMessageMapper.selectOverdueMsg(0, t);
    }

    @Override
    public List<MmMessage> selectOverdueMsgBySend(int t) {
        return this.mmMessageMapper.selectOverdueMsg(1, t);
    }
}

